package com.lwlk.zdk.service.PostService.impl;

import com.alibaba.fastjson.JSONObject;
import com.lwlk.zdk.common.exception.handler.GlobalExceptionHandler;
import com.lwlk.zdk.mapper.T.TDisEnterpriseMapper;
import com.lwlk.zdk.mapper.T.TDisPlatformMapper;
import com.lwlk.zdk.mapper.pw.pwCheckTheDutyIssueMapper;
import com.lwlk.zdk.mapper.pw.pwCheckTheDutyMessageMapper;
import com.lwlk.zdk.mapper.pw.pwMessageMapper;
import com.lwlk.zdk.mapper.sys.sysEnterpriseMapper;
import com.lwlk.zdk.mapper.sys.sysUserMapper;
import com.lwlk.zdk.model.pw.pwCheckTheDutyIssue;
import com.lwlk.zdk.model.pw.pwCheckTheDutyMessage;
import com.lwlk.zdk.model.pw.pwMessage;
import com.lwlk.zdk.model.task.pwTask;
import com.lwlk.zdk.service.PostService.PostMessageService;
import com.lwlk.zdk.service.Task.TimeService;
import com.lwlk.zdk.service.Task.impl.TaskServiceImpl;
import com.lwlk.zdk.util.HttpClientUtil;
import com.lwlk.zdk.util.HttpClientUtils;
import com.lwlk.zdk.util.PropUtils;
import com.lwlk.zdk.util.RandomNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PostMessageServiceImpl implements PostMessageService {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @Autowired
    pwCheckTheDutyIssueMapper pwCheckTheDutyIssueMapper;
    @Autowired
    pwMessageMapper pwMessageMapper;
    @Autowired
    pwCheckTheDutyMessageMapper pwCheckTheDutyMessageMapper;
    @Autowired
    private TaskServiceImpl taskServices;
    @Autowired
    private sysUserMapper sysUserMapper;
    @Autowired
    private sysEnterpriseMapper sysEnterpriseMapper;
    @Autowired
    TimeService timeService;
    @Autowired
    TDisPlatformMapper disPlatformMapper;
    @Autowired
    TDisEnterpriseMapper disEnterpriseMapper;

    private final static String port = PropUtils.getString("ports");
    private final static String Ip = PropUtils.getString("Ip");
    private final static String clientCode = PropUtils.getString("clientCode");

    @Override
    public int add(pwCheckTheDutyIssue pwCheckTheDutyIssue) {
        int i = pwCheckTheDutyIssueMapper.insertSelective(pwCheckTheDutyIssue);
        return i;
    }

    @Override
    public int deleteBatch(Integer integer) {
        int i = pwCheckTheDutyIssueMapper.deleteBatch(integer);
        return i;
    }

    @Override
    public int update(pwCheckTheDutyIssue pwCheckTheDutyIssue) {
        int i = pwCheckTheDutyIssueMapper.updateByPrimaryKeySelective(pwCheckTheDutyIssue);
        return i;
    }

    @Override
    public pwCheckTheDutyIssue details(Integer id) {
        pwCheckTheDutyIssue pwCheckTheDutyIssue = pwCheckTheDutyIssueMapper.selectByPrimaryKey(id);
        return pwCheckTheDutyIssue;
    }

    @Override
    public List<pwCheckTheDutyIssue> query(String topic, String creator) {
        List<pwCheckTheDutyIssue> pwCheckTheDutyIssueList = pwCheckTheDutyIssueMapper.selectDim(topic, creator);
        return pwCheckTheDutyIssueList;
    }


    @Override
    public List<pwMessage> selectDim(Integer platformId, Date startTime, Integer isReply, Date endTime) {
        List<pwMessage> pwCheckTheDutyIssueList = pwMessageMapper.selectDim(platformId, startTime, isReply, endTime);
        return pwCheckTheDutyIssueList;
    }

    @Override
    public pwCheckTheDutyIssue selectOne(String topicType) {
        pwCheckTheDutyIssue pwCheckTheDutyIssue = pwCheckTheDutyIssueMapper.selectOne(topicType);
        return pwCheckTheDutyIssue;
    }

    @Override
    public int insertCheck(pwCheckTheDutyMessage pwCheckTheDutyMessage) {
        int i = pwCheckTheDutyMessageMapper.insertSelective(pwCheckTheDutyMessage);
        return i;
    }



    @Override
    public int updateContent(Date updateTime, Integer msgId, String content) {
        int i=pwCheckTheDutyMessageMapper.updateContent(updateTime,msgId,content);
        return i;
    }

    @Override
    public int insertMessage(pwMessage pwMessage1) {
        int i=pwMessageMapper.insertSelective(pwMessage1);
        return i;
    }

    @Override
    public String selectPlatformId(int i) {
        String platformId=pwMessageMapper.selectPlatformId(i);
        return platformId;
    }

    @Override
    public int updateMessage(int i, String messageObjectTypeId) {
        int ss=pwMessageMapper.updateMessage(i,messageObjectTypeId);
        return ss;
    }

    @Override
    public int updateResult(Date responseTime, Integer msgId, String content,Integer count) {
        int i=pwMessageMapper.updateResult(responseTime,msgId,content,count);
        return i;
    }

    @Override
    public int updateEnterpriseId(String roleType,String eId, int i) {
        int ii=pwMessageMapper.updateEnterpriseId(roleType,eId,i);
        return ii;
    }

    @Override
    public List<Map<String, Object>> selectSubordinate(String startTime, String endTime,Integer uId,String messageObjectType,Integer platformIds) {
        List<Map<String,Object>>subordinateList=pwMessageMapper.selectSubordinate(startTime,endTime,uId,messageObjectType,platformIds);
        return subordinateList;
    }

    @Override
    public int updateObjectType(Integer msgId, String objectId) {
        int i=pwCheckTheDutyMessageMapper.updateObjectType(msgId,objectId);
        return i;
    }

    @Override
    public List<Map> selectMessageDetails(Integer messageId) {

        return pwMessageMapper.selectMessageDetails(messageId);
    }

    @Override
    public Integer selectResponseSum(Integer msgId) {
        return pwMessageMapper.selectResponseSum(msgId);
    }

    @Override
    public List<Map<String, Object>> selectPlatformRecord(Integer uId, Integer platformId, String checkTime) {
        return pwCheckTheDutyMessageMapper.selectPlatformRecord(uId,platformId,checkTime);
    }


    public int addDuty(Integer id) {
        try {
            pwTask p = taskServices.selectAll(id);
            String question=pwCheckTheDutyIssueMapper.selectQuestion(p.getChdId());
            String[] ids = p.getAssessObjectDetails().split(",");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat ds = new SimpleDateFormat("yyyy-MM-dd ");
            String path="/dis/v1/platform/check";
            Date now = new Date();//当前时间
            Date executeTime=df.parse(ds.format(now)+" "+p.getCheckTime());//执行时间
            pwCheckTheDutyMessage pwCheckTheDutyMessage = new pwCheckTheDutyMessage();
            String objectTypeId=p.getAssessObject().equals("0X01")?"1":p.getAssessObject().equals("0X02")?"2":p.getAssessObject().equals("0X03")?"3":"";
                for (String s : ids) {
                    pwCheckTheDutyMessage.setPlatformId(Integer.parseInt(s));//被查岗的平台id
                    pwCheckTheDutyMessage.setChdId(p.getChdId());//查岗问题id
                    pwCheckTheDutyMessage.setRoleType(p.getAssessObject());//被查岗的角色
                    pwCheckTheDutyMessage.setCheckTime(executeTime);//具体查岗的时间
                    pwCheckTheDutyMessage.setContentType(0);//未应答
                    pwCheckTheDutyMessage.setAssessPeriod(p.getAssessPeriod());//查岗周期
                    pwCheckTheDutyMessage.setUUID(p.getUUID());
                    pwCheckTheDutyMessage.setEnterpriseId(Integer.parseInt(p.getAssessObjectDetails()));
                    pwCheckTheDutyMessage.setPlatformIds(p.getPlatformIds());//平台id
                    pwCheckTheDutyMessage.setuId(p.getuId());
                    int i = pwCheckTheDutyMessageMapper.insertSelective(pwCheckTheDutyMessage);
                }
                if (p.getAssessObject().equals("0X01")) {
                    for (String s : ids) {
                        String regionCode = disPlatformMapper.selectAccessCode(p.getPlatformIds());
                        String region=regionCode.substring(0,4);
                        String messageObjectTypeId =region+ RandomNumber.randomString(4,false);
                        int i = pwCheckTheDutyMessageMapper.updateAccessCode(messageObjectTypeId, p.getUUID(), s);
                        Map map=new HashMap();
                        map.put("msgId",pwCheckTheDutyMessage.getMsgId());
                        map.put("question",question);//问题
                        map.put("objectId",messageObjectTypeId);
                        map.put("pid",p.getPlatformIds());
                        map.put("objectType",objectTypeId);
                        Map<String,String>headMap=new HashMap<>();
                        headMap.put("clientCode",clientCode);
                        HashMap hashMap=new HashMap();
                        JSONObject jsonString = new JSONObject();
                        String body= jsonString.toJSONString(map);
                        //String url="http://"+Ip+":"+port+"/dis/v1/platform/check";

                        String result= HttpClientUtils.doPostTestThree(path,headMap,hashMap,body);
                        log.info(result);

                    }
                }
                if (p.getAssessObject().equals("0X02")) {//单一企业
                   for (String s : ids) {
                        String accessCode = disEnterpriseMapper.selectAccessCode(Integer.parseInt(s));
                         int i = pwCheckTheDutyMessageMapper.updateAccessCode(accessCode, p.getUUID(), s);
                       Map map=new HashMap();
                       map.put("msgId",i);
                       map.put("question",question);//问题
                       map.put("objectId",accessCode);
                       map.put("objectType",objectTypeId);
                       map.put("pid",p.getPlatformIds());
                       Map<String,String>headMap=new HashMap<>();
                       headMap.put("clientCode",clientCode);
                       JSONObject jsonString = new JSONObject();
                       String body= jsonString.toJSONString(map);
                       HashMap hashMap=new HashMap();
                       //String url="http://"+Ip+":"+port+"/dis/v1/platform/check";
                       String result= HttpClientUtils.doPostTestThree(path,headMap,hashMap,body);
                       log.info(result);
                    }
                }
                if(p.getAssessObject().equals("0X03")){//所有企业
                    for (String s : ids) {
                        String accessCode = "0X000000000000000000000000";
                        int i = pwCheckTheDutyMessageMapper.updateAccessCode(accessCode, p.getUUID(), s);
                        Map map=new HashMap();
                        map.put("msgId",i);
                        map.put("question",question);//问题
                        map.put("objectId",accessCode);
                        map.put("objectType",objectTypeId);
                        map.put("pid",p.getPlatformIds());
                        Map<String,String>headMap=new HashMap<>();
                        headMap.put("clientCode",clientCode);
                        HashMap hashMap=new HashMap();
                        JSONObject jsonString = new JSONObject();
                        String body= jsonString.toJSONString(map);
                        //String url="http://"+Ip+":"+port+"/dis/v1/platform/check";
                        String result= HttpClientUtils.doPostTestThree(path,headMap,hashMap,body);
                        log.info(result);
                    }
                }
               Calendar c;
               c=Calendar.getInstance();
                if (p.getAssessPeriod().equals("日")){
                    c.setTime(executeTime);
                    c.add(Calendar.DAY_OF_MONTH, 1);//明日的执行日期
                    timeService.CreateCheckTime(c.getTime(), id);
                }
                if (p.getAssessPeriod().equals("月")){
                    c.setTime(executeTime);
                    c.add(Calendar.DAY_OF_MONTH, 1);//延长到下个月的执行日期
                    timeService.CreateCheckTime(c.getTime(), id);
                }
                if (p.getAssessPeriod().equals("周")){
                    c.setTime(executeTime);
                    c.add(Calendar.DAY_OF_MONTH, 7);//延长到下周的执行日期
                    timeService.CreateCheckTime(c.getTime(),id);
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
           return 1;
    }
}

